package com.example.demo.service;

import com.alibaba.fastjson.JSON;
import com.example.demo.VO.User;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;

/**
 * @description:
 * @author: ZZZ
 * @time: 2023/9/12 18:30
 */
@Component
public class MQProducer {
    @Autowired
    public DefaultMQProducer producer;

    private int id = 0;

    @Scheduled(cron = "0/5 * * * * *")
    public void send() throws MQBrokerException, RemotingException, InterruptedException, MQClientException {

        String key = "" + id++;
        User user = new User();
        user.setId(key);
        user.setName("我是生产者");
        Message msg = new Message("Topic1", "Tag1", JSON.toJSONString(user).getBytes());
        msg.setKeys(key);
        //5.发送消息
        SendResult result = producer.send(msg);
        //发送状态
        SendStatus status = result.getSendStatus();

        System.out.println("发送结果:" + JSON.toJSONString(status));

    }



}
